<template>
    <ElUpload v-show="modelValue == ''" list-type="picture-card" :auto-upload="false" :limit="1"
        :on-change="handleChange" :file-list="fileList" :show-file-list="false" :on-remove="handleRemove">
        <ElIcon>
            <Plus />
        </ElIcon>
        <template #file>

        </template>
    </ElUpload>
    <div class="relative" v-if="modelValue" @mouseenter="showDeleteButton = true"
        @mouseleave="showDeleteButton = false">
        <img class="size-37 object-cover rounded" :src="fileList.length>0?fileList[0].url:props.modelValue" alt="" />
        <div class="size-37 rounded absolute top-0 flex justify-center items-center" style="background: #00000011;"
            @click="handleRemove(fileList[0])" v-show="showDeleteButton">
            <ElIcon size="20" color="#fff">
                <Delete />
            </ElIcon>
        </div>
    </div>

</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElIcon, ElUpload, ElMessage } from 'element-plus'
import { Delete, Message, Plus } from '@element-plus/icons-vue'

import type { UploadFile, UploadFiles } from 'element-plus'
import { uploadImage } from '@/api/utils'
/** 文件名 */
const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})
/** emit */
const emit = defineEmits(['update:modelValue'])
function updateFileName() {
    if (fileList.value.length > 0) {
        emit('update:modelValue', fileList.value[0].name)
    } else {
        emit('update:modelValue', '')
    }
}
/** 文件列表 */
const fileList = ref<UploadFile[]>([])
/** 控制删除按钮显示 */
const showDeleteButton = ref(false)

/** 文件变化 */
const handleChange = (file: UploadFile, files: UploadFiles) => {
    /** 文件大小处理 */
    if (file.size && file.size > 5 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过5MB')
        fileList.value = fileList.value.filter(item => item.uid !== file.uid)
        return
    }
    /** 文件类型处理 */
    if (file.raw?.type != 'image/jpeg' && file.raw?.type != 'image/png') {
        ElMessage.error('请上传jpg或者png格式的图片')
        fileList.value = fileList.value.filter(item => item.uid !== file.uid)
        return
    }
    fileList.value = [...files]
    /** 更新props */
    updateFileName()
}
/** 删除文件 */
const handleRemove = (file: UploadFile) => {
    fileList.value = fileList.value.filter(item => item.uid !== file.uid)
    /** 更新props */
    updateFileName()
    /** 关闭删除按钮 */
    showDeleteButton.value = false
}

async function uploadImg() {
    const res: any = await uploadImage(fileList.value[0].raw as File)
    if (res.code == 200) {
        return res.data
    } else {
        ElMessage.error(res.msg)
        return ''
    }
}
defineExpose({
    uploadImg
})
</script>